#!/bin/bash

###########################################################################
#	$Id$
###########################################################################

prog="archive.sh"

tar_path=tar
zip_path=zip
rar_path=rar
unzip_path=unzip
unrar_path=unrar
gzip_path=gzip
bzip2_path=bzip2

function action() {
	echo "+ $1"
	$1
}

function error() {
	echo "ERROR: $1"
	exit 1
}

# print incoming CGI variables
echo "# CGI_HOME: $CGI_HOME"
echo "# CGI_ARCHIVER: $CGI_ARCHIVER"
echo "# CGI_COMPRESSOR: $CGI_COMPRESSOR"

# change home directory if needed
if [ ! $CGI_HOME = "" ]; then
	action "mkdir -p $CGI_HOME"
	action "cd $CGI_HOME"
	echo "# PWD: $PWD"
fi

ACTION=$1
ARCHIVE_PATH=$2

# print defined action and path
echo "# ACTION: $ACTION"
echo "# ARCHIVE_PATH: $ARCHIVE_PATH"


case $ACTION in


	add)

		ARCHIVE_CONTENT=$3
		echo "# ARCHIVE_CONTENT: $ARCHIVE_CONTENT"

		case $CGI_ARCHIVER in
			tar)
				if [ -f $ARCHIVE_PATH ]; then
					ADD_PARAMS="--append"
				else
					ADD_PARAMS="--create"
				fi

				action "$tar_path $ADD_PARAMS --verbose --file=$ARCHIVE_PATH $ARCHIVE_CONTENT"

				ADD_PARAMS=""
			;;
			zip)
				action "$zip_path $ARCHIVE_PATH $ARCHIVE_CONTENT"
			;;
			rar)
				action "$rar_path a -idq $ARCHIVE_PATH $ARCHIVE_CONTENT"
			;;
		esac

		case $CGI_COMPRESSOR in
			gzip)
				action "$gzip_path $ARCHIVE_PATH"
			;;
			bzip2)
				action "$bzip2_path $ARCHIVE_PATH"
			;;
		esac
	;;


	extract)

		EXTRACT_TO=$3
		echo "# EXTRACT_TO: $EXTRACT_TO"

		action "mkdir -p $EXTRACT_TO"

		case $CGI_ARCHIVER in
			tar)
				if [ ! "$EXTRACT_TO" = "" ]; then
					EXTRACT_PARAMS="--directory $EXTRACT_TO"
				fi

				case $CGI_COMPRESSOR in
					gzip)
						action "$tar_path -xzf $ARCHIVE_PATH $EXTRACT_PARAMS"
					;;
					bzip2)
						action "$tar_path -xjf $ARCHIVE_PATH $EXTRACT_PARAMS"
					;;
					*)
						action "$tar_path -xf $ARCHIVE_PATH $EXTRACT_PARAMS"
					;;
				esac

				EXTRACT_PARAMS=""
			;;
			zip)
				if [ ! "$EXTRACT_TO" = "" ]; then
					EXTRACT_PARAMS="-d $EXTRACT_TO"
				fi

				action "$unzip_path -o $ARCHIVE_PATH $EXTRACT_PARAMS"

				EXTRACT_PARAMS=""
			;;
			rar)
				action "$unrar_path e -idq -y $ARCHIVE_PATH $EXTRACT_TO"
			;;
			*)
				error "unknown archiver"
			;;
		esac
	;;


	list)
		case $CGI_ARCHIVER in
			tar)
				action "$tar_path -tvf $ARCHIVE_PATH"
			;;
			zip)
				action "$unzip_path -l $ARCHIVE_PATH"
			;;
			rar)
				action "$rar_path l $ARCHIVE_PATH"
			;;
			*)
				error "unknown archiver"
			;;
		esac
	;;

	*)
		echo "###################################################################"
		echo "Usage."
		echo "-------------------------------------------------------------------"
		echo "1. add"
		echo "$prog add ARCHIVE_PATH 'ARCHIVE_CONTENT'"
		echo "---"
		echo "2. extract"
		echo "$prog extract ARCHIVE_PATH EXTRACT_TO"
		echo "---"
		echo "3. list"
		echo "$prog list ARCHIVE_PATH"
		echo "###################################################################"
	;;

esac
